﻿using System.Web.Mvc;
using LeadMaster.Helpers;
using LeadMaster.DAL;
using System.Linq;
using System;
using System.Web.Security;
using LeadMaster.Models;
using LeadMaster.ViewModels;
using System.Collections.Generic;
using System.Data.Entity;

namespace LeadMaster.Controllers
{
    public class RegionsController : Controller
    {
      private DunsmoreContext db = new DunsmoreContext();
        
      //
        // GET: /Regions/

        public ActionResult Index()
        {
          IEnumerable<Regions> ListRegions = db.Regions;
          return View(ListRegions);
        }

        //
        // GET: /Regions/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Regions/Create

        public ActionResult Create()
        {
            Regions region = new Regions();
            return View(region);
        }

        //
        // POST: /Regions/Create

        [HttpPost]
        public ActionResult Create(Regions region)
        {
            try
            {
              region.Postcodes = region.Postcodes.Replace(" ", "").ToUpper();
              db.Regions.Add(region);
              db.SaveChanges();
              return RedirectToAction("Index");
            }
            catch(Exception e)
            {
              ViewBag.errmsg = e.Message;
              return View();
            }
        }

        //
        // GET: /Regions/Edit/5

        public ActionResult Edit(int id)
        {
          Regions region = db.Regions.Find(id);
            return View(region);
        }

        //
        // POST: /Regions/Edit/5

        [HttpPost]
        public ActionResult Edit(Regions region)
        {
            try
            {
              region.Postcodes = region.Postcodes.Replace(" ", "").ToUpper();
              db.Entry(region).State = EntityState.Modified;
              db.SaveChanges();
              return RedirectToAction("Index");
            }
            catch (Exception e)
            {
              ViewBag.errmsg = e.InnerException.Message;
              return View();
            }
        }

        //
        // GET: /Regions/Delete/5

        public ActionResult Delete(int id)
        {
          Regions region = db.Regions.Find(id);
            return View(region);
        }


        [HttpPost]
        public ActionResult Delete(Regions regions)
        {
            try
            {
              Regions region = db.Regions.Find(regions.RegionsID);
              db.Regions.Remove(region);
              db.SaveChanges();
              return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                return View();
            }
        }
    }
}
